/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.documents.main.action;

import com.documents.common.core.PageBean;
import com.documents.common.core.action.BaseActionSupport;
import com.documents.common.util.*;
import com.documents.htmlobj.CountryObj;
import com.documents.htmlobj.ProductObj;
import com.documents.htmlobj.PropertyObj;
import com.documents.pojo.*;
import com.documents.service.country.CountryService;
import com.documents.service.document.DocumentFormatOrderService;
import com.documents.service.document.DocumentGroupService;
import com.documents.service.document.DocumentIndexTreeService;
import com.documents.service.document.DocumentService;
import com.documents.service.document.DocumentTypeService;
import com.documents.service.document.FillPointsService;
import com.documents.service.product.ProductService;
import com.documents.service.updown.FileUpDownService;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

/**
 *
 * @author Administrator
 */
public class DocumentAction extends BaseActionSupport implements ServletRequestAware {

    private Document document;
    private DocumentType documentType;
    private Country contry;
    private Case ca;
    private Product product;
    private int page = 1;
    private PageBean pageBean;
    private int pageSize = 20;
    private List<DocumentType> typeList;
    private List<Country> countryList;
    private List<Product> productList;
    private CountryService countryService;
    private List<PropertyObj> propertyList;
    private DocumentTypeService documentTypeService;
    private DocumentGroupService documentGroupService;
    private ProductService productService;
    private List<Accessory> accessoryList;
    private DocumentService documentService;
    private FillPointsService pointsService;
    private FillPoints points;
    private List<FillPoints> pointsList;
    private File[] file;
    private String[] fileName;
    private String dlFileName;
    private String trueName;
    private FileUpDownService fileUpDownService;
    private String actionURI;
    private int document_id;
    private int point_id;
    private static String DOCUMENT = "document";
    private DocumentFormatOrderService documentFromatOrderService;
    private int groupid;
    private String groupname;
    private List<CountryObj> clist;
    private List<ProductObj> proList;
    private DocumentIndexTreeService documentIndexTreeService;
    private String delstrings;

    public String getDelstrings() {
        return delstrings;
    }

    public void setDelstrings(String delstrings) {
        this.delstrings = delstrings;
    }

    public String getGroupname() {
        return groupname;
    }

    public void setGroupname(String groupname) {
        this.groupname = groupname;
    }

    public DocumentIndexTreeService getDocumentIndexTreeService() {
        return documentIndexTreeService;
    }

    public void setDocumentIndexTreeService(DocumentIndexTreeService documentIndexTreeService) {
        this.documentIndexTreeService = documentIndexTreeService;
    }

    public List<ProductObj> getProList() {
        return proList;
    }

    public void setProList(List<ProductObj> proList) {
        this.proList = proList;
    }

    public int getPoint_id() {
        return point_id;
    }

    public void setPoint_id(int point_id) {
        this.point_id = point_id;
    }

    public List<PropertyObj> getPropertyList() {
        return propertyList;
    }

    public void setPropertyList(List<PropertyObj> propertyList) {
        this.propertyList = propertyList;
    }

    public List<CountryObj> getClist() {
        return clist;
    }

    public void setClist(List<CountryObj> clist) {
        this.clist = clist;
    }

    public String add_input() {
        actionURI = "save";
        this.createMenus();
        return SUCCESS;
    }

    public int getDocument_id() {
        return document_id;
    }

    public void setDocument_id(int document_id) {
        this.document_id = document_id;
    }

    public FillPoints getPoints() {
        return this.points;
    }

    public void setPoints(FillPoints points) {
        this.points = points;
    }

    public List<FillPoints> getPointsList() {
        return pointsList;
    }

    public void setPointsList(List<FillPoints> pointsList) {
        this.pointsList = pointsList;
    }

    public FillPointsService getPointsService() {
        return pointsService;
    }

    public void setPointsService(FillPointsService pointsService) {
        this.pointsService = pointsService;
    }

    public String save() {
        if (document != null) {
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            document.setCreateTime(timestamp);
            document.setSubmitTime(timestamp);
            String num = StringUtil.getRequestNo();
            document.setNum(num);
            if (document.getProduct().getId() > -1) {
                Product p = productService.get(document.getProduct().getId());
                if (p != null) {
                    document.setProductName(p.getName());
                    document.setProductCode(p.getCode());
                }
            }
            if (document.getCountry().getId() > -1) {
                Country c = countryService.get(document.getCountry().getId());
                if (c != null) {
                    document.setCountryName(c.getName());
                    document.setCountryCode(c.getCode());
                }
            }
            if (document.getDocumentType().getId() > -1) {
                DocumentType dg = documentTypeService.get(document.getDocumentType().getId());
                if (dg != null) {
                    document.setTypeName(dg.getName());
                }
            }
            documentService.save(document);
            if (this.getFile() != null) {
//                document = documentService.get(document.getId());
                document = documentService.findUnique("num=?", new Object[]{num});
                fileUpload(document);// 调用上传文件方法
//                documentFromatOrderService.createConverOrder(document.getId());
            }

            return SUCCESS;

        } else {

            addActionMessage("dc is null!");
            return ERROR;
        }

    }

    public void fileUpload(Document dt) {
        System.out.println("文件大小" + this.getFile().length);
        System.out.println("文件有" + this.getFile());
        // HttpServletRequest request = ServletActionContext.getRequest();
        // String[] paths = request.getParameterValues("file");
        // this.setFile(paths);
        fileName = fileName[0].toString().split("%");
        for (int i = 0; i < this.getFile().length; i++) {
            String name = StringUtil.generateFileName(fileName[i + 1]);
//            name=name.substring(0, name.indexOf("."));
            String tmpurl = "/document/" + name;
            String url = FileStorage.getUpLoadPath(ServletActionContext.getRequest())
                    + tmpurl;

            File dstFile = new File(url);
            try {
                FileUtils.forceMkdir(dstFile.getParentFile());
            } catch (IOException e) {
                logger.error("创建文件失败！");
                e.printStackTrace();
            }// 创建上传tempFile文件所在的父目录文件;
            System.out.println("文件路径" + dstFile);
            FileUtility.copy(file[i], dstFile);
            Accessory accessory = new Accessory();
            accessory.setName(name);
            accessory.setTruename(fileName[i + 1]);

            accessory.setTableId(dt.getId());
            accessory.setTableName("document");
            accessory.setUploadDate(dt.getSubmitTime());
//            accessory.setUrl(url);
            accessory.setUrl(tmpurl);
//            accessory.setVersion(dt.getVersion());
            fileUpDownService.addUpFileInfo(accessory);
        }

    }

    public String down() throws Exception {

        try {
            String url = FileStorage.getUpLoadPath(ServletActionContext.getRequest()) + "/document/" + this.dlFileName;
            Accessory accessory = fileUpDownService.getAccessoryByNameAndVersion(this.dlFileName, 0);

            
            this.trueName = new String(accessory.getName());
//            String url = ServletActionContext.getServletContext().getRealPath("/upload/document") + "/" + this.dlFileName;
            File file = new File(url);
            if (!file.exists() || !file.isFile()) {
                return ERROR;
            }
            this.dlFileName = "/upload/document/" + this.dlFileName;
            return SUCCESS;
        } catch (Exception e) {
            return ERROR;
        }

    }

    public String delete() {
        Document tmpdocument = documentService.findUnique("id=?", new Object[]{document_id});
        String dnum = tmpdocument.getNum();

        boolean fileisok = fileUpDownService.deleteByIdAndTableName(
                document_id, DOCUMENT, FileStorage.getUpLoadPath(ServletActionContext.getRequest()));


        documentService.delById(document_id);
        return SUCCESS;
    }

    public String show() {

        document = documentService.get(document_id);
        accessoryList = fileUpDownService.getAccessoryByTableNameAndTableIdAndVersion(DOCUMENT, document_id, 0);
        pointsList = pointsService.find("document_id=?", new Object[]{document_id}, "id");
        if (document == null) {
            return ERROR;
        }
        return SUCCESS;
    }

    public String update() throws Exception {

        if (document != null) {
            Document documenttemp = documentService.get(document.getId());
            String num = documenttemp.getNum();
            if (document.getProduct().getId() > -1) {
                Product p = productService.get(document.getProduct().getId());
                if (p != null) {
                    documenttemp.setProductName(p.getName());
                    documenttemp.setProductCode(p.getCode());
                }
            }
            if (document.getCountry().getId() > -1) {
                Country c = countryService.get(document.getCountry().getId());
                if (c != null) {
                    documenttemp.setCountryName(c.getName());
                    documenttemp.setCountryCode(c.getCode());
                }
            }
            if (document.getDocumentType().getId() > -1) {
                DocumentType dg = documentTypeService.get(document.getDocumentType().getId());
                if (dg != null) {
                    documenttemp.setTypeName(dg.getName());
                }
            }

            documenttemp.setExperience(document.getExperience());
            documenttemp.setFeature(document.getFeature());
            documenttemp.setFillPoints(document.getFillPoints());
            documentService.update(documenttemp);


            // 删除就附件
            if (delstrings != null && !delstrings.equals("")) {
                String[] delAccessrieStrings = delstrings.split("%");
                for (String s : delAccessrieStrings) {
                    boolean fileisok = fileUpDownService.deleteById(Integer.parseInt(s), FileStorage.getUpLoadPath(ServletActionContext.getRequest()));

                    fileUpDownService.delAcessoryByAcessoryId(Integer.parseInt(s));

                }

            }





            if (this.getFile() != null) {
//                document = documentService.get(document.getId());

                document = documentService.findUnique("num=?", new Object[]{num});
                fileUpload(document);// 调用上传文件方法
//                documentFromatOrderService.createConverOrder(document.getId());


            }

            return SUCCESS;

        } else {

            addActionMessage("dc is null!");
            return ERROR;
        }

    }

    public String updateInput() throws Exception {
        actionURI = "update";
        this.createMenus();
        document = this.documentService.get(document_id);
        accessoryList = fileUpDownService.getAccessoryByTableNameAndTableIdAndVersion(DOCUMENT, document_id, 0);
        if (document == null) {
            return ERROR;
        } else {
            return SUCCESS;
        }
    }

    public String fillPoints() throws Exception {
        //  actionURI = "update";

        pageBean = pointsService.getPageBeanByDocId(page, pageSize, document_id);
        return SUCCESS;

    }

    public String addPoints() {
        actionURI = "savePoints";
        document = documentService.get(document_id);
        return SUCCESS;
    }

    public String savePoints() {
        pointsService.save(points);
        return SUCCESS;
    }

    public String viewPoints() throws Exception {
        actionURI = "updatePoints";
        points = this.pointsService.get(point_id);
        if (points == null) {
            return ERROR;
        } else {
            return SUCCESS;
        }
    }

    public String updatePoints() throws Exception {
        this.pointsService.update(points);
        document = documentService.get(points.getDocument_id());
        return SUCCESS;

    }

    public String deletePoints() {
        FillPoints tmp = pointsService.findUnique("id=?", new Object[]{point_id});
        if (tmp != null) {
            pointsService.delById(point_id);

        }
        return SUCCESS;
    }

    public InputStream getInputStream() {

        return ServletActionContext.getServletContext().getResourceAsStream(
                "/" + dlFileName);

    }

    public InputStream getDownloadFile() {
        return ServletActionContext.getServletContext().getResourceAsStream(this.getDlFileName());
    }

    public String getActionURI() {
        return actionURI;
    }

    public void setActionURI(String actionURI) {
        this.actionURI = actionURI;
    }

    public String getDlFileName() {
        return dlFileName;
    }

    public void setDlFileName(String dlFileName) {
        this.dlFileName = dlFileName;
    }

    public File[] getFile() {
        return file;
    }

    public void setFile(File[] file) {
        this.file = file;
    }

    public String[] getFileName() {
        return fileName;
    }

    public void setFileName(String[] fileName) {
        this.fileName = fileName;
    }

    public FileUpDownService getFileUpDownService() {
        return fileUpDownService;
    }

    public void setFileUpDownService(FileUpDownService fileUpDownService) {
        this.fileUpDownService = fileUpDownService;
    }

    public String getTrueName() {
        return trueName;
    }

    public void setTrueName(String trueName) {

        this.trueName = trueName;
    }

    public void createMenus() {
//        clist = countryService.createList();
//        productList = productService.findAll();
        propertyList = documentGroupService.createList();
//        proList = documentIndexTreeService.createList();
//        this.getTypeByGroupId(groupid);
        this.getPropertyByGroupName(groupname);
    }

    public String list() {

        this.createMenus();


        pageBean = documentService.getPageBean(page, pageSize, document, groupname);
        
        if (document != null) {
            if(document.getDocumentType()!=null)
            {
                  DocumentType dt= documentTypeService.get(document.getDocumentType().getId());
                  document.setTypeName(dt.getName());
            }
          
            document.setName(filter(document.getName()));
            if (document.getName() != null) {
                if (document.getName().indexOf("<iframe") > 0 || document.getName().indexOf("<frame") > 0) {
                    document.setName(document.getName().replace("<", "&lt;"));
                }
            }

           

            groupname = filter(groupname);
        }

        return SUCCESS;
    }

    public String filter(String value) {
        if (value == null) {
            return null;
        }
        StringBuffer result = new StringBuffer(value.length());
        for (int i = 0; i < value.length(); ++i) {
            switch (value.charAt(i)) {
                case '<':
                    result.append("&lt;");
                    break;
                case '>':
                    result.append("&gt;");
                    break;
                case '"':
                    result.append("&quot;");
                    break;
                case '\'':
                    result.append("&#39;");
                    break;
                case '%':
                    result.append("&#37;");
                    break;
                case ';':
                    result.append("&#59;");
                    break;
                case '(':
                    result.append("&#40;");
                    break;
                case ')':
                    result.append("&#41;");
                    break;
                case '&':
                    result.append("&amp;");
                    break;
                case '+':
                    result.append("&#43;");
                    break;

                default:
                    result.append(value.charAt(i));
                    break;
            }

        }
        return result.toString();
    }

    public void getPropertyByGroupName(String groupname) {
        groupname = filter(groupname);
        if (groupname != null && !groupname.equals("")) {
            DocumentGroup dg = documentGroupService.findUnique("name=?", new Object[]{groupname});
            List<DocumentType> typeslist = new ArrayList();
            if (dg != null && dg.getLevel() == 1) {
                List<DocumentGroup> dg2 = this.documentGroupService.find("pid=?", new Object[]{dg.getId()}, "id");

                for (DocumentGroup o : dg2) {
                    Set types = o.getDocumentTypes();
                    typeslist.addAll(types);
                }
            }
            if (dg != null && dg.getLevel() == 2) {
                Set types = dg.getDocumentTypes();
                typeslist.addAll(types);

            }
            typeList = typeslist;
        } else {
            typeList = documentTypeService.findAll();
            typeList.remove(0);
        }

    }

    public String listByGroupId() {

     



        pageBean = documentService.getPageBean(page, pageSize, groupid);
        DocumentGroup dp= documentGroupService.get(groupid);
           groupname = dp.getName();
        this.createMenus();
//        DocumentGroup dg = documentGroupService.findUnique("id=?", new Object[]{groupid});
//      
//        if (dg.getLevel() == 1) {
//            DocumentGroup dg2 = documentGroupService.findUnique("id=?", new Object[]{dg.getId()});
//            pageBean.setPageSize(pageSize);
//            pageBean.setCurrentPage(page);
//            Set types = dg.getDocumentTypes();
//            List<DocumentType> typeslist = new ArrayList(types);
//            if (typeslist != null && typeslist.size() > 0) {
//                int size = typeslist.size();
//
//                Object[] parameters = new Object[size];
//
//                int paramIndex = 0;
//                String sql = "";
//
//                for (DocumentType t : typeslist) {
//
//                    sql += "type=? or ";
//                    parameters[paramIndex] = t.getId();
//                    paramIndex++;
//
//                }
//                sql = sql.substring(0, sql.lastIndexOf("or"));
//                Long allRow = documentService.findTotalCount(sql, parameters);
//                int totalPage = PageBean.countTotalPage(pageSize, allRow.intValue()); // 总页数
//                pageBean.setAllRow(allRow.intValue());
//                pageBean.setTotalPage(totalPage);
//                List<Document> list = documentService.findWithPaging(sql, parameters, "id", page - 1, pageSize);
//                pageBean.setList(list);
//            }
//
//        }
//        if (dg.getLevel() == 2) {
//            pageBean.setPageSize(pageSize);
//            pageBean.setCurrentPage(page);
//            Set types = dg.getDocumentTypes();
//            List<DocumentType> typeslist = new ArrayList(types);
//            if (typeslist != null && typeslist.size() > 0) {
//                int size = typeslist.size();
//                Object[] parameters = new Object[size];
//
//                int paramIndex = 0;
//                String sql = "";
//
//                for (DocumentType t : typeslist) {
//
//                    sql += "type=? or ";
//                    parameters[paramIndex] = t.getId();
//                    paramIndex++;
//
//                }
//                sql = sql.substring(0, sql.lastIndexOf("or"));
//                Long allRow = documentService.findTotalCount(sql, parameters);
//                int totalPage = PageBean.countTotalPage(pageSize, allRow.intValue()); // 总页数
//                pageBean.setAllRow(allRow.intValue());
//                pageBean.setTotalPage(totalPage);
//                List<Document> list = documentService.findWithPaging(sql, parameters, "id", page - 1, pageSize);
//                pageBean.setList(list);
//            }
//
//        }
        return SUCCESS;
    }

    public DocumentService getDocumentService() {
        return documentService;
    }

    public void setDocumentService(DocumentService documentService) {
        this.documentService = documentService;
    }

    public List<Accessory> getAccessoryList() {
        return accessoryList;
    }

    public void setAccessoryList(List<Accessory> accessoryList) {
        this.accessoryList = accessoryList;
    }

    public CountryService getCountryService() {
        return countryService;
    }

    public void setCountryService(CountryService countryService) {
        this.countryService = countryService;
    }

    public DocumentTypeService getDocumentTypeService() {
        return documentTypeService;
    }

    public void setDocumentTypeService(DocumentTypeService documentTypeService) {
        this.documentTypeService = documentTypeService;
    }

    public ProductService getProductService() {
        return productService;
    }

    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    public List<Country> getCountryList() {
        return countryList;
    }

    public void setCountryList(List<Country> countryList) {
        this.countryList = countryList;
    }

    public List<Product> getProductList() {
        return productList;
    }

    public void setProductList(List<Product> productList) {
        this.productList = productList;
    }

    public List<DocumentType> getTypeList() {
        return typeList;
    }

    public void setTypeList(List<DocumentType> typeList) {
        this.typeList = typeList;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public PageBean getPageBean() {
        return pageBean;
    }

    public void setPageBean(PageBean pageBean) {
        this.pageBean = pageBean;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public Case getCa() {
        return ca;
    }

    public void setCa(Case ca) {
        this.ca = ca;
    }

    public Country getContry() {
        return contry;
    }

    public void setContry(Country contry) {
        this.contry = contry;
    }

    public Document getDocument() {
        return document;
    }

    public void setDocument(Document document) {
        this.document = document;
    }

    public DocumentType getDocumentType() {
        return documentType;
    }

    public void setDocumentType(DocumentType documentType) {
        this.documentType = documentType;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public DocumentGroupService getDocumentGroupService() {
        return documentGroupService;
    }

    public void setDocumentGroupService(DocumentGroupService documentGroupService) {
        this.documentGroupService = documentGroupService;
    }

    public DocumentFormatOrderService getDocumentFromatOrderService() {
        return documentFromatOrderService;
    }

    public void setDocumentFromatOrderService(DocumentFormatOrderService documentFromatOrderService) {
        this.documentFromatOrderService = documentFromatOrderService;
    }

    public void getTypeByGroupId(int groupId) {
        if (groupId > 0) {
            typeList = this.documentTypeService.getTypeByGroupId(groupid);
        } else {
            typeList = documentTypeService.findAll();
        }

//        if (!list.isEmpty()) {
//            JSONArray jsonArrayTemp = new JSONArray();
//            for (DocumentType s : list) {
//                JSONObject jsonTemp = new JSONObject();
//                jsonTemp.put("id", s.getId());
//                jsonTemp.put("pId", s.getPid());
//                jsonTemp.put("name", s.getName());
//                jsonTemp.put("des", s.getDes());
//      jsonArrayTemp.put(jsonTemp);
//            }
//
//            ServletActionContext.getResponse().setContentType("text/json; charset=utf-8");
//            try {
//                ServletActionContext.getResponse().getWriter().write(jsonArrayTemp.toString());
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }

    }

    public int getGroupid() {
        return groupid;
    }

    public void setGroupid(int groupid) {
        this.groupid = groupid;
    }


}
